<script lang="ts" setup>
import {onMounted, reactive, ref} from 'vue'
import {useLoginUserStore} from '@/stores/useLoginUserStore.ts'
import {type CascaderProps, message} from 'ant-design-vue'
import router from '@/router'
import {getTeachAndLearn, register} from "@/api/userController.ts";

// 用于接受表单输入的值
const formState = reactive<API.RegisterRequest>({
  userAccount: '',
  userPassword: '',
  checkPassword: '',
  teach: [],
  learn: [],
})

const loginUserStore = useLoginUserStore()
const options: CascaderProps['options'] = ref()

//提交表单
const handleSubmit = async (values: any) => {
  // 校验两次输入的密码是否一致
  if (values.userPassword !== values.checkPassword) {
    message.error('两次输入的密码不一致')
    return
  }
  //实际得到的是二维数组，需处理
  const payload = {
    ...values,
    // 假设只想提交最后一级（子节点）的值
    teach: values.teach ? values.teach.map((item: string[]) => item[item.length - 1]) : [],
    learn: values.learn ? values.learn.map((item: string[]) => item[item.length - 1]) : []
  };
  const res = await register(payload)
  // 注册成功，跳转到登录页面
  if (res.data.code === 0 && res.data.data) {
    message.success('注册成功')
    await router.push({
      path: '/login',
      replace: true,
    })
  } else {
    message.error('注册失败，' + res.data.message)
  }
}
const getTeachAndLearnOptions = async () => {
  const res = await getTeachAndLearn()
  if (res.data.code === 0 && res.data.data) {
    // 使用 Object.entries 将对象转换为可遍历的键值对数组
    options.value = Object.entries(res.data.data).map(([parentKey, childrenValues]) => {
      return {
        value: parentKey, // 使用父级的键作为 value，如 "计算机"
        label: parentKey, // 使用父级的键作为显示标签，如 "计算机"
        children: childrenValues.map(childValue => {
          return {
            value: childValue, // 使用子项的值作为 value，如 "java"
            label: childValue  // 使用子项的值作为显示标签，如 "java"
          }
        })
      }
    })
    console.log('转换后的 options:', options.value) // 添加日志，调试时非常有用
  } else {
    message.error('获取选项失败' + res.data.message)
  }
}
onMounted(() => {
  getTeachAndLearnOptions()
})
</script>
<template>
  <div id="userRegisterPage">
    <h2 class="title">厚米匹配 - 用户注册</h2>
    <div class="desc">找寻志同道合的厚米</div>
    <a-form :model="formState" name="basic" autocomplete="off" @finish="handleSubmit">
      <a-form-item name="userAccount"
                   :rules="[{ required: true, message: '请输入账号' }, { min: 3, message: '账号长度不能小于 3 位' }]">
        <a-input v-model:value="formState.userAccount" placeholder="请输入账号"/>
      </a-form-item>
      <a-form-item
          name="userPassword"
          :rules="[
          { required: true, message: '请输入密码' },
          { min: 3, message: '密码长度不能小于 3 位' },
        ]"
      >
        <a-input-password v-model:value="formState.userPassword" placeholder="请输入密码"/>
      </a-form-item>
      <a-form-item
          name="checkPassword"
          :rules="[
          { required: true, message: '请输入确认密码' },
          { min: 3, message: '确认密码长度不能小于 3 位' },
        ]"
      >
        <a-input-password v-model:value="formState.checkPassword" placeholder="请输入确认密码"/>
      </a-form-item>
      <a-form-item
          name="teach">
        <a-cascader
            v-model:value="formState.teach"
            style="width: 100%"
            multiple
            max-tag-count="responsive"
            :options="options"
            placeholder="我能教"
        />
      </a-form-item>
      <a-form-item
          name="learn">
        <a-cascader
            v-model:value="formState.learn"
            style="width: 100%"
            multiple
            max-tag-count="responsive"
            :options="options"
            placeholder="我想学"
        />
      </a-form-item>


      <div class="tips">
        已有账号？
        <RouterLink to="/login">去登录</RouterLink>
      </div>
      <a-form-item>
        <a-button type="primary" html-type="submit" style="width: 100%">注册</a-button>
      </a-form-item>
    </a-form>
  </div>
</template>


<style scoped>
#userRegisterPage {
  max-width: 360px;
  margin: 50px auto;
}

.title {
  text-align: center;
  margin-bottom: 16px;
}

.desc {
  text-align: center;
  color: #bbb;
  margin-bottom: 16px;
}

.tips {
  color: #bbb;
  text-align: right;
  font-size: 13px;
  margin-bottom: 16px;
}
</style>
